package util;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.UUID;

public class DataSourceUtil {
    //数据库连接池需实现javax.sql.DataSource接口，DBCP连接池是javax.sql.DataSource接口的具体实现
    private static DataSource ds = new BasicDataSource();
    //使用静态代码块创建数据库连接池
    static{
        try{
            //加载dbcpconfig.properties配置文件
            InputStream in = DataSourceUtil.class.getClassLoader().getResourceAsStream("dataSource.properties");
            System.out.println(in);
            Properties prop = new Properties();
            prop.load(in);

            //创建数据源
            ds = BasicDataSourceFactory.createDataSource(prop);
        }catch (Exception e){
            throw new ExceptionInInitializerError(e);
        }
    }

    /**
     * @Method:getConnection
     * @Description:从数据源中获取数据库连接
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {

        //从数据源中获取数据库连接
        return ds.getConnection();
    }

    /**
     * @Method:release
     * @Description:释放资源(数据库连接对象conn,负责执行SQL命令的Statement对象，存储查询结果的ResultSet对象)
     * @param conn
     * @param st
     * @param rs
     */
    public static void release(Connection conn, Statement st, ResultSet rs){
        if (rs!=null){
            try {
                //关闭存储查询结果的ResultSet对象
                rs.close();
            }catch (Exception e){
                e.printStackTrace();
            }
            rs = null;
        }
        if (st!=null){
            try {
                st.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                //将Connection连接对象还给数据库连接池
                conn.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }


}
